# coding:utf-8
# @Time    : 2021/12/10 8:54
# @Author  : Martin


from page_object.base import PageItems
from util.read_file import get_approve_data


class OnlineFloorGiftPage(PageItems):
    _base_url = "/nspas-web-in/processRoleFilter.do?businessTemplateId=NSOA23334"

    def click_floor_type(self, txt):
        """
        选择阶梯类型
        :param txt:
        :return:
        """
        self.click('xpath', f'//input[@name="ruleBonusMode"][@value="{txt}"]')

    def click_add_floor(self):
        """
        点击增加阶梯
        :param txt:
        :return:
        """
        self.click('link text', '增加阶梯')

    def input_count_limit(self, floor_num, count):
        """
        输入阶梯次数信息
        :param floor_num:
        :param count:
        :return:
        """
        # if start:
        #     self.js_input('css selector',
        #                f'#floorPresentRule>table:nth-child({floor_num} input[name="floorPresentRule.ladderStart"]')
        # if end:
        self.input('css selector',
                   f'#floorPresentRule>table:nth-child({floor_num}) input[name="floorPresentRule.ladderEnd"]', count)

    def input_time_limit(self, floor_num, start, end):
        """
        输入阶梯时间信息
        :param start:
        :param end:
        :return:
        """
        if start:
            self.js_input(f'#floorPresentRule>table:nth-child({floor_num}) input[name="floorPresentRule.ladderStart"]',
                          start)
        if end:
            self.js_input(f'#floorPresentRule>table:nth-child({floor_num}) input[name="floorPresentRule.ladderEnd"]',
                          end)

    def click_add_gifts(self, floor_num):
        """
        点击添加赠品，进入赠品输入页面
        :param floor_num:
        :return:
        """
        self.click('css selector', f'#floorPresentRule>table:nth-child({floor_num}) a[onclick="tradeScopeSet(this)"]')

    def click_add_gift(self):
        """
        点击添加，新增赠品行输入
        :param floor_num:
        :return:
        """
        self.click('link text', '增加')
        # self.click('xpath', f'//a[@onlick="presentScopeAdd(\'{floor_num}\')"]')

    def click_confirm(self, floor_num):
        """
        点击确定，保存
        :return:
        """
        # 点击确定
        self.click('xpath', f'//a[@onclick="tradeScopeOk(\'{floor_num}\')"]')

    def input_gifts(self, floor_num, gift_num, gift_type, code, count, total, price):

        # 选择赠品类型
        self.select('css selector',
                    f'#detailinfoPresentScope{floor_num}>#detailedtablePresentScope:nth-child({gift_num}) select['
                    f'name="activityPresentScope.giftType"]', gift_type)

        # 输入商品编码
        self.input('css selector',
                   f'#detailinfoPresentScope{floor_num}>#detailedtablePresentScope:nth-child({gift_num}) '
                   f'input[name="activityPresentScope.commodityCode"]', code)

        # 输入单次赠送数量
        self.js_input(
            f'#detailinfoPresentScope{floor_num}>#detailedtablePresentScope:nth-child({gift_num}) '
            f'input[name="activityPresentScope.singleAmount"]', count, event='onblur')

        # 输入赠送总数量
        self.input('css selector',
                   f'#detailinfoPresentScope{floor_num}>#detailedtablePresentScope:nth-child({gift_num}) '
                   f'input[name="activityPresentScope.totalAmount"]', total)
        if gift_type == '1':
            # 输入宣传价
            self.input('css selector',
                       f'#detailinfoPresentScope{floor_num}>#detailedtablePresentScope:nth-child({gift_num}) '
                       f'input[name="activityPresentScope.balanceAmount"]', price)

    def input_act_rule(self, floor_type, floors):
        """
        输入赠品优惠规则信息
        :param floor_type:
        :param floors:
        :return:
        """
        self.click_floor_type(floor_type)

        for floor_num, floor in enumerate(floors):
            self.click_add_floor()
            floor_num += 1
            # 输入层级限制信息
            if floor_type == '6':
                self.input_count_limit(floor_num, **floor['limit'])
            elif floor_type == '5':
                self.input_time_limit(floor_num, **floor['limit'])
            # 点击添加赠品
            self.click_add_gifts(floor_num)
            # 输入赠品信息
            for gift_num, gift in enumerate(floor['gifts']):
                gift_num += 1
                self.click_add_gift()
                self.input_gifts(floor_num, gift_num, **gift)
            self.click_confirm(floor_num)

    @staticmethod
    def get_approve_head_create():
        """
        获取总部新建审批流账号数据
        :return:
        """
        return get_approve_data('online_floor_gift', 'head', 'create')

    def add_single(self, params):
        """
        添加单品包含
        :param params:商品范围列表
        :return:
        """
        self._select_relation('包含')
        for param in params:
            self._input_commdty_scope(**param)
            self.click('id', 'cmmdCodeAdd')
        self.click('link text', '添加到商品范围')

    def go_to_approve(self):
        """
        首次点击提交去审批
        :return:
        """
        self.click('id', 'submitBtn')

    def gift_remain_amount(self):
        return self.get_element_attr('id', 'remainAmount', 'value')

    @staticmethod
    def cal_lock_amount(total, price):
        return total * price

    def cal_all_lock_amount(self, act_info):
        i = 0
        rule_info = act_info['input_act_rule']['floors']
        lock_amount = 0
        while True:
            param = rule_info[i]
            for gift in param['gifts']:
                if gift['gift_type'] == '1':
                    total = gift['total']
                    price = gift['price']
                    lock_amount += self.cal_lock_amount(total, price)
                else:
                    continue
            i += 1
            if i == len(rule_info):
                break
        self.logger.info(f"赠品预锁额度为<{lock_amount}>")
        return lock_amount


if __name__ == '__main__':
    pass
    # js = '{"input_act_rule":[{"limit":10,"option":1,"gifts":[{"gift_type":1,"code":"000000000761203340","count":1,"total":2,"pub_price":1.11}]},{"limit":20,"option":1,"gifts":[{"gift_type":1,"code":"000000000104697611","count":1,"total":1,"pub_price":3.22}]}]}'

    # print(OnlineOrderGiftPage.cal_all_lock_amount(json.loads(js)))
    # print(1.11 * 2)
    # pass
